package com.wm.code_gerenator;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 代码生成
 *
 * @author wm_yu
 * @date 2020/04/06
 */
public class CodeGenerator {


    /**
     * 包名
     */
    public static final String PACKAGE_NAME = "com.wm";

    /**
     * 模块名
     */
    public static final String MODULE_NAME = "bb";

    /**
     * 数据库名
     */
    public static final String DB_NAME = "liunian_blog";

    /**
     * 数据库表前缀
     */
    public static final String[] TABLE_PREFIX = {};

    /**
     * 需要生成的表名，不填则生成全部表
     */
    public static final String[] TABLE_NAME = {"t_recommend"};

    /**
     * 获取当前项目的路径
     */
    public static final String PROJECT_PATH = System.getProperty("user.dir") + "/code-generator";


    /**
     * 代码存储路径
     */
    public static final String CODE_SAVE_PATH = PROJECT_PATH + "/src/main/java/" + StringUtils.join((PACKAGE_NAME + "." + MODULE_NAME).split("\\."), "/");


    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();

        gc.setOutputDir(PROJECT_PATH + "/src/main/java");
        gc.setAuthor("wm_yu");
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setServiceName("%sService");
        gc.setBaseColumnList(true);
        gc.setBaseResultMap(true);
        gc.setDateType(DateType.ONLY_DATE);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/" + DB_NAME + "?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setTypeConvert(new MySqlTypeConvert() {
            @Override
            public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                //将tinyint格式改为Integer类型
                if (fieldType.toLowerCase().contains("tinyint")) {
                    return DbColumnType.INTEGER;
                }
                return super.processTypeConvert(globalConfig, fieldType);
            }
        });
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(MODULE_NAME);
        pc.setParent(PACKAGE_NAME);
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                HashMap<String, Object> hashMap = new HashMap<>(10);
                hashMap.put("parentPackage", PACKAGE_NAME + "." + MODULE_NAME);
                this.setMap(hashMap);
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        //mapper xml类
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return CODE_SAVE_PATH + "/resources/mapper/" + tableInfo.getEntityName().replace("t_","") + "Mapper" + StringPool.DOT_XML;
            }
        });

        //service类
        focList.add(new FileOutConfig("/templates/service.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return CODE_SAVE_PATH + "/service/" + tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;
            }
        });

        //dao 类
        focList.add(new FileOutConfig("/templates/dao.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return CODE_SAVE_PATH + "/dao/" + tableInfo.getEntityName() + "DAO" + StringPool.DOT_JAVA;
            }
        });

        //domain
        focList.add(new FileOutConfig("/templates/domain.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return CODE_SAVE_PATH + "/domain/" + tableInfo.getEntityName() + "DO" + StringPool.DOT_JAVA;
            }
        });
        //query查询类
        focList.add(new FileOutConfig("/templates/query.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return CODE_SAVE_PATH + "/query/" + tableInfo.getEntityName() + "Query" + StringPool.DOT_JAVA;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(TABLE_PREFIX);
        strategy.setNaming(NamingStrategy.underline_to_camel);
        //数据库下划线转驼峰格式
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        //数据库实体类的公共字段,没有就注释掉,按需求添加
        //strategy.setSuperEntityClass("com.hfepay.common.data.mybatis.bean.BaseEntity");
        //添加lombok注解
        strategy.setEntityLombokModel(true);
        //rest风格生成http形式
        strategy.setRestControllerStyle(true);
        //controller 父类,不需要就注释掉,按需求添加
        //strategy.setSuperControllerClass("com.hfepay.common.web.controller.BaseController");
        if (TABLE_NAME.length > 0) {
            strategy.setInclude(TABLE_NAME);
        }

        //自定义基础的Entity类，公共字段 ，填入将在entity中不出现,如果注释了父类,这个也注释掉
        //strategy.setSuperEntityColumns("id", "version", "create_time", "update_time");
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
        //删除自己不需要的目录
        deleteDir(new File(CODE_SAVE_PATH + "/service/impl"));
    }

    private static void deleteDir(File dir) {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteDir(files[i]);
            }
        }
        dir.delete();
    }

}
